import { isDate, isNumber, isString } from "@/utils";
import { DatePicker as ArcoDatePicker } from "@arco-design/web-react";
import useFormContext from "@arco-design/web-react/es/Form/hooks/useContext";
import type { Dayjs } from "dayjs";

interface DatePickerProps {
	value?: string | number | Date | Dayjs;
	onChange?: (value: string | number | Date | Dayjs) => void;
	minDate?: string | number | Date | Dayjs;
	maxDate?: string | number | Date | Dayjs;
	placeholder?: string;
	className?: string;
}

export default function DatePicker({
	value,
	onChange,
	minDate,
	maxDate,
	placeholder = "请选择日期",
	className,
}: DatePickerProps) {
	const { disabled: formDisabled } = useFormContext();

	const disabledDate = (current: Dayjs) => {
		let flag = false;
		if (minDate) flag ||= current.isBefore(minDate);
		if (maxDate) flag ||= current.isAfter(maxDate);
		return flag;
	};

	const handleChange = (dateString: string, date: Dayjs) => {
		if (!onChange) return;

		if (isString(dateString)) onChange(dateString);
		else if (isNumber(dateString)) onChange(date.unix());
		else if (isDate(dateString)) onChange(date.toDate());
		else onChange(date);
	};

	return (
		<ArcoDatePicker
			value={value}
			placeholder={placeholder}
			disabled={formDisabled}
			disabledDate={disabledDate}
			onChange={handleChange}
			className={className}
		/>
	);
}
